﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.CarInsurance;
using CE.Company;
using CE.Mail;
using CE.InputOut;

public partial class car_insurance_quote_results_table : MyLanguageAndSessionBasePage
{
    int _currentRow = 0;
    string _redirectUrl = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.QuoteResultsTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.QuoteResultsKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.QuoteResultsDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer) && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                Response.Redirect("sign-in.aspx");
            }
        }
        else
        {
            Response.Redirect("sign-in.aspx");
        }

        if (Session[General.CarId] == null || Session[General.CarPolicyId] == null)
        {
            string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive").ToString();

            Response.Redirect("~/car-insurance/");

        }
        else
        {
            hplCarResults.NavigateUrl = "";
        }

        if (Session[General.IsCarRestoreResult] != null)
        {
            hplProfile.NavigateUrl = "";
            hplCarDetails.NavigateUrl = "";
            ibtRunNewQuote.Visible = true;
        }
        else
        {
            ibtRunNewQuote.Visible = false;
        }

        if (!Page.IsPostBack)
        {
            ibtNoMatchBack.Visible = false;
            ibtSubmit.Attributes.Add("OnClick", "javascript:if (Page_ClientValidate()) { return confirm('By pressing the submit button, you authorise GluayGluay.com to save your personal information.'); } return false;");

            HyperLink _lnkTest = new HyperLink();
           _lnkTest = null;

            #region Validation Effect
            divUserRefDetail.Visible = false; //Sakthi
            txtFullName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtFullName.ClientID + "','" + rfvFullName.ClientID + "','" + revFullName.ClientID + "')");
            txtVehicleNo.Attributes.Add("onblur", "this.value=removeSpaces(this.value);ShowValidationEffectTwo('" + txtVehicleNo.ClientID + "','" + rfvVehicleNo.ClientID + "','" + revVehicleNo.ClientID + "')");

            txtCallMeFullName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtCallMeFullName.ClientID + "','" + rfvCallMeFullName.ClientID + "','" + revCallMeFullName.ClientID + "')");
            ddlCallMeTime.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCallMeTime.ClientID + "','" + rfvCallMeTime.ClientID + "')");

            #endregion

            lblRMessage.Text = "Result: No Matches Found!";
            if (Session[General.UserId] != null)
            {
                lblUserName.Text = Session[General.UserName].ToString();
                txtCallMeFullName.Text = Session[General.UserName].ToString();
                usrCallMePhoneNo.PhoneNo = Session[General.UserPhoneNo].ToString();
            }
            txtCallMeFullName.ReadOnly = true;
            Session[CE.Global.General.CarResultId] = null;

            if (Session[General.IsCarRestoreResult] != null)
            {
                divSummaryBox.Visible = true;
                divFormSelection.Visible = false;
            }
            else
            {
                divSummaryBox.Visible = false;
                divFormSelection.Visible = true;
            }

            ShowQuoteSummary();

            if (lblInsuranceType.Text == "1")
            {
                divStep.Attributes.Add("class", "ThreeSteps");
                divPath.Attributes.Add("class", "StepThree");
            }
            else
            {
                divStep.Attributes.Add("class", "TwoSteps");
                divPath.Attributes.Add("class", "StepTwo");
            }

            if (Session[General.UserId] != null && !CheckViewCount())
            {
                divMessage.Visible = true;
                lblMessage.Visible = true;
                imgInstantBuy.Visible = false;
                imgInstantBuy.ImageUrl = "";
                lblMessage.Text = "<br />Due to speed optimization reasons, each user is restricted to 5 quotes per day.<br />Please visit us tomorrow.";
                return;
            }
            else
            {
                divMessage.Visible = false;
                lblMessage.Visible = false;

                imgInstantBuy.ImageUrl = Resources.ImageResource.BuyDirectUrl;//"~/images/bg/heading_buydirect.png";
                CalculatePremium();

                if (Session[General.UserId] != null)
                {
                    Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());
                }
                else
                {
                    Cache.Remove("CarResult" + Session[General.CarId].ToString());
                }

                if (ViewState["SortOrder"] == null)
                {
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                if (ViewState["SortExpression"] == null)
                {
                    ViewState["SortExpression"] = "";
                }

                if (Request.Params["sortby"] != null)
                {
                    int _sortBy = 0;
                    if (Int32.TryParse(Request.Params["sortby"].ToString(), out _sortBy))
                    {
                        string _sortExpress = "";
                        string _sortOrder = "";

                        if (_sortBy == 0)
                        {
                            _sortExpress = "AnnualPremium";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 1)
                        {
                            _sortExpress = "CompanyName";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 2)
                        {
                            _sortExpress = "PackageName";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 3)
                        {
                            _sortExpress = "TPPD";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 4)
                        {
                            _sortExpress = "TPBIP";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 5)
                        {
                            //_sortExpress = "CashAllowance";
                            _sortExpress = "PADriver";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 6)
                        {
                            _sortExpress = "PAPassenger";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 7)
                        {
                            _sortExpress = "MedicalExpense";
                            _sortOrder = " ASC";
                        }
                        else
                        {
                            _sortExpress = "BailBond";
                            _sortOrder = " ASC";
                        }

                        ViewState["SortExpression"] = _sortExpress;
                        if (_sortOrder == " ASC")
                            ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                        else
                            ViewState["SortOrder"] = SortDirection.Descending.ToString();
                    }
                    else
                    {
                        ViewState["SortExpression"] = "AnnualPremium";
                        //ViewState["SortOrder"] = " ASC";
                        ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                    }
                }
                else
                {
                    ViewState["SortExpression"] = "PromotionPrice";
                    //ViewState["SortOrder"] = " ASC";
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                //NEED TO EDIT
                ResultsQuotesDataBind();
                LogUserViewedHistory();
            }
        }
    }

    private void GetReferenceUser(Int64 UserId, Int64 CarId, string ProductType)
    {
    }

    private void ShowQuoteSummary()
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarPolicy _carpolicy = new CarPolicy();

        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        CarPolicyDB _carpolicydb = new CarPolicyDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Int64 _refceuserid = 0;
        Int64 _carid = 0;

        if (Session[General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
        }

        if (Session[General.CarId] != null)
        {
            _carid = Convert.ToInt64(Session[General.CarId].ToString());
            _cardetail = _cardetaildb.GetCar(_carid, _refceuserid);
        }

        _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);

        if (_cardetail != null && _carpolicy != null)
        {
            lblYrofManufacture.Text = _cardetail.ManufactYear.ToString();
            lblYrofManTop.Text = _cardetail.ManufactYear.ToString();

            lblCarMakemodel.Text = _cardetail.MakeModelDesc;
            lblCarMakemodelTop.Text = _cardetail.MakeModelDesc;
            if (lblCarMakemodelTop.Text.Length > 40)
            {
                lblCarMakemodelTop.Font.Size = new FontUnit(8.0d);
                lblCarMakemodelTop.ToolTip = _cardetail.MakeModelDesc;
            }
            switch (_carpolicy.InsuranceType)
            {
                case 10: //class 1
                    lblInsuranceType.Text = "1";
                    break;
                case 11: //class 1 (low cost)
                    lblInsuranceType.Text = "1+";
                    break;
                case 21: //class 2+
                    lblInsuranceType.Text = "2+";
                    break;
                case 31: //class 3+
                    lblInsuranceType.Text = "3+";
                    break;
                case 30: //class 3
                    lblInsuranceType.Text = "3";
                    break;
            }

            lblSumInsured.Text = _carpolicy.SumInsured.ToString();


            lblRedPlate.Text = _carpolicy.IsRedPlate ? "Yes" : "No";
            lblCTPL.Text = _carpolicy.IsCTPL ? "Yes" : "No";
            lblNCBValue.Text = _carpolicy.NCDPercent.ToString() + "%";
            lblNCBvalueTop.Text = _carpolicy.NCDPercent.ToString() + "%";
            lblVehicleType.Text = _carpolicy.VehicleType == 110 ? "Private" : "Public";
            lblClass.Text = lblInsuranceType.Text;
            lblAddDriver.Text = _carpolicy.IsAddDriver ? "Yes" : "No";
            lblCommencementdate.Text = _carpolicy.CoverageCommenceDate.ToString("dd-MMM-yyyy");
            lblCommencementdateTop.Text = _carpolicy.CoverageCommenceDate.ToString("dd-MMM-yyyy");

            //Foreigner Case - send Mail 
            if (_cardetaildb.GetForeignerCase(_cardetail.Info8, _cardetail.Info7) > 0)
            {
                //SendMailNotification(_cardetail);
            }
        }

        _profile = null;
        _profiledb = null;
        _cardetail = null;
        _cardetaildb = null;
        _carpolicy = null;
        _carpolicydb = null;
    }

    private bool CheckViewCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCarInsuranceResultViewCountByDateUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", Session[General.UserId].ToString());
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue > 0;
    }

    private bool CheckMailSendCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCINoMatchFoundCountByMailSendStatus]";

        SortedList _spList = new SortedList();
        _spList.Add("@ProductType", "CI");

        DataTable _dtResult = _db.GetDataTableBySP(_spName, _spList);

        Int32 _retValue = 0;
        if (_dtResult.Rows.Count > 0)
        {
            _retValue = Convert.ToInt32(_dtResult.Rows[0]["MailSendCount"].ToString());
        }
        return _retValue < 12;
    }

    private bool CheckFirstTimeQuote()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocAutoEmailFirstQuoteInsertUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", Session[General.UserId].ToString());
        _spList.Add("@EmailType", 100);
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue == 1;
    }

    //Old One
    private bool SendMailFirstQuoteToUser()
    {
        bool _retVal = false;
        string _emailTo = Session[CE.Global.General.UserEmail].ToString();
        string _customername = Session[CE.Global.General.UserName].ToString();
        string _emailSubject = "First Car Insurance Quote - " + DateTime.Now.ToString();
        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
        CompanyInformation _company = new CompanyInformation();
        CompanyInformationDB _companydb = new CompanyInformationDB();
        _company = _companydb.GetCompanyInformation(3);
        string _companyAddress = "";
        string _emailaddress = "";
        string _websiteaddress = "";
        if (_company != null)
        {
            _companyAddress = _company.Address1;
            _emailaddress = _company.EmailAddress;
            _websiteaddress = _company.Website;
        }
        _company = null;
        _companydb = null;

        _mailBody = "Dear " + _customername + ", <br /><br />Thank you for using GluayGluay.com for the first time.";
        _mailBody += "<br /><br />You are able to view this quote through our Members Area by clicking on the link below. <br /><br /> <a href='http://www.gluaygluay.com' target='_blank'>http://www.gluaygluay.com</a>.";
        _mailBody += "<br /><br /> Enter your Email and Password to login to the Members Area, located on the top right of the page.";
        _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@gluaygluay.com'>support@gluaygluay.com</a>.";
        _mailBody += "<br /><br />Best Regards,<br /><br />Your GluayGluay.com Team<br/>Customer Support - Thailand/International";
        _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
        _mailBody += "<br /><hr />";
        _mailBody += _companyAddress;
        _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";
        if (MyMailManager.SendCRMMessage(_emailTo, _emailSubject, _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    private Int32 CalculatePremium()
    {
        MyDatabase _db = new MyDatabase();

        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        BKIDetailDB bki = new BKIDetailDB();

        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@RefUserId", _userId);

        Int32 _result = 0;


        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);


        if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
        {
            if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AZCPProviderCompanyID"))
                _result = _db.ExecuteNonSqlSP("[sprocAZCPCarInsuranceCalculation]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAProviderCompanyID"))
                _result = _db.ExecuteNonSqlSP("[sprocAXACarInsuranceCalculation]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGProviderCompanyID"))
                _result = _db.ExecuteNonSqlSP("[sprocMSIGCarInsuranceCalculation]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGProviderCompanyID"))
                _result = _db.ExecuteNonSqlSP("[sprocLMGCarInsuranceCalculation]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisProviderCompanyID"))
                _result = _db.ExecuteNonSqlSP("[sprocChartisCarInsuranceCalculation]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatProviderCompanyID"))
                _result = _db.ExecuteNonSqlSP("[sprocTVVCarInsuranceCalculation]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIProviderCompanyID"))
            {
                try
                {
                    bki.BKICalculation(_carId, _userId);
                }
                catch (Exception ex)
                {
                }

                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationBKI]", _sPara);
            }
        }
        else
        {
            //====Test Web Service
            try
            {
                bki.BKICalculation(_carId, _userId);
            }
            catch
            {
            }

            _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);
        }
        return _result;
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogResultViewedHistory("CI", Request, "Car Insurance results.");
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView();
        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);
        }

        string _strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            _strSort = " ASC";
        }
        else
        {
            _strSort = " DESC";
        }
        dv.Sort = ViewState["SortExpression"].ToString() + _strSort;
        gvCarResult.DataSource = dv;
        gvCarResult.DataBind();
    }

    private bool SendMailToUser()
    {
        bool _retVal = false;
        return _retVal;
    }

    private void SendCarInsuranceQuote(DataTable dtResult)
    {
        if (CheckFirstTimeQuote())
        {
            string _filename = GenerateGridResultPDF();
            if (!SendMailFirstQuoteToUser())
            {
            }
        }
    }

    private string GenerateGridResultPDF()
    {
        return "";
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        if (_dtResult.Rows.Count > 0)
        {
            imgInstantBuy.Visible = true;
            imgInstantBuy.ImageUrl = Resources.ImageResource.BuyDirectUrl;
            gvCarResult.Visible = true;
            divHeadingbuydirect.Visible = true;
            divUserRefDetail.Visible = false;

        }
        else
        {
            gvCarResult.Visible = false;
            divHeadingbuydirect.Visible = false;
            divUserRefDetail.Visible = true;
            Session["UMMSG"] = "CI,5000";
            _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
            Response.Redirect(_redirectUrl);

            //}
            imgInstantBuy.Visible = false;
            imgInstantBuy.ImageUrl = Resources.ImageResource.BuyDirectNoResultUrl; 

        }

        if (Session[General.UserId] != null)
        {
            Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
        }
        else
        {
            Cache["CarResult" + Session[General.CarId].ToString()] = _dtResult;
        }

        SendMailToUser();
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        ExportGridView("CarInsuranceQuote", gvCarResult, "Car Insurance Quote");
    }

    public void ExportGridView(string fileName, GridView gvExport, string headerText)
    {
        string attachment = "attachment; filename=" + fileName + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        // Create a form to contain the grid
        HtmlForm frm = new HtmlForm();
        frm.InnerHtml = headerText;
        gvExport.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gvExport);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

    protected void btnNewCarInsurance_Click(object sender, EventArgs e)
    {
        if (Session[General.UserId] == null)
        {
            General.ClearAllSession(this.Page, "LOGOUT");
        }
        else
        {
            General.ClearAllSession(this.Page, "CI");
        }
        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/", Page);
        Response.Redirect(_redirectUrl);
    }

    protected void ibtRunNewQuote_Click(object sender, EventArgs e)
    {
        CE.Global.General.ClearAllSession(this.Page, "AL");
        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/default.aspx", Page);
        Response.Redirect(_redirectUrl);
    }

    protected void ibtBack_Click(object sender, ImageClickEventArgs e)
    {
        string _previouspage = string.Empty;
        switch (lblInsuranceType.Text)
        {
            case "1":
                _previouspage = "~/car-insurance/profile.aspx";
                break;
            case "1+":
                _previouspage = "~/car-insurance/class-1single.aspx";
                break;
            case "2+":
                _previouspage = "~/car-insurance/class-2plus.aspx";
                break;
            case "3+":
                _previouspage = "~/car-insurance/class-3plus.aspx";
                break;
            case "3":
                _previouspage = "~/car-insurance/class-3.aspx";
                break;
            default:
                _previouspage = "~/car-insurance/profile.aspx";
                break;

        }
        _redirectUrl = CE.Global.General.GetUrl(_previouspage, Page);
        Response.Redirect(_redirectUrl);
    }

    protected void ibtNoMatchBack_Click(object sender, ImageClickEventArgs e)
    {
        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/", Page);
        Response.Redirect(_redirectUrl);
    }
    
    protected void gvCarResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = cell.Controls[0] as LinkButton;
                    if (button != null)
                    {
                        Image imageSort = new Image();
                        imageSort.ImageUrl = "/Images/icon/clear.gif";
                        imageSort.AlternateText = "clear";

                        HtmlGenericControl gv = new HtmlGenericControl("span");
                        Label lnkName = new Label();
                        lnkName.Text = button.Text;

                        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == button.CommandArgument.ToString())
                        {
                            if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() == SortDirection.Descending.ToString())
                            {
                                imageSort.ImageUrl = "/Images/icon/Sort_Down.gif";
                                imageSort.AlternateText = "SortDown";
                            }
                            else
                            {
                                imageSort.ImageUrl = "/Images/icon/Sort_Up.gif";
                                imageSort.AlternateText = "SortUp";
                            }
                        }
                        gv.Controls.Add(lnkName);
                        gv.Controls.Add(imageSort);
                        button.Controls.Add(gv);
                    }
                }
            }

            //Creat Custome Header
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderGridRow =
            new GridViewRow(0, 0, DataControlRowType.Header,
            DataControlRowState.Insert);

            TableCell HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src='/images/arrows/arrow-down.png\' alt=\"down\" />" + Resources.CarInsuranceResultPage.OwnDamage + "<img src=\"/images/arrows/arrow-down.png\" class=\"imgabs\" alt=\"down\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "green_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 4;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"/images/arrows/arrow-down.png\" class=\"imgabs\" alt=\"down\" /> " + Resources.CarInsuranceResultPage.ThirdPartyLiability + "<img src=\"/images/arrows/arrow-down.png\" class=\"imgabs\" alt=\"down\" /><br/>" + Resources.CarInsuranceResultPage.PerAccident;
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "blue_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"/images/arrows/arrow-down.png\" class=\"imgabs\" alt=\"down\" />" + Resources.CarInsuranceResultPage.AdditionalCovers + "<img src=\"/images/arrows/arrow-down.png\" class=\"imgabs\" alt=\"down\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "gold_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            //HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            gvCarResult.Controls[0].Controls.AddAt
            (0, HeaderGridRow);
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            controls_usrMoreInfoDropdownButton btnMoreInfo = (controls_usrMoreInfoDropdownButton)e.Row.FindControl("ibtMoreInfo");
            ImageButton ibtBuyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");

            btnMoreInfo.RowId = "NewRow" + ((e.Row.RowIndex * 2) + 1).ToString();
            ibtBuyNow.CommandArgument = e.Row.RowIndex.ToString();
        }
    }

    protected int GetRowNumber(string ctrlId)
    {
        int num = ctrlId.LastIndexOf("ctl");
        string index = ctrlId.Substring(num + 3, 2);
        int resultTemp = 0;
        int result = -1;
        if (int.TryParse(index, out resultTemp))
        {
            result = resultTemp;
        }
        return result;
    }

    protected void gvCarResult_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("BuyNow"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = gvCarResult.DataKeys[index];

            Session[CE.Global.General.CarResultId] = myData[0].ToString();
            Session[CE.Global.General.ProviderCompanyId] = myData[1].ToString();
            Int64 _resultId = Convert.ToInt64(myData[0].ToString());
            Int64 _companyId = Convert.ToInt64(myData[1].ToString());
            LogUserSelectHistory(_resultId, _companyId);

            /* update Language*/
            CarDetailTHDB cardetail = new CarDetailTHDB();
            Boolean language = cardetail.UpdateLanguage(Convert.ToInt64(Session[General.CarId]), Session["Language"].ToString());

            if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 11)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/azcp_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 12)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/msig_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 16)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/axa_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 29)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/lmg_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 31)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/chartis_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 32)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/bki_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 33)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/mti_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 35)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/krungthai_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 39)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/mittare_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 41)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/ksk_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 43)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/synmunkong_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 45)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/viriyah_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 46)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/tms_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 50)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/scsmg_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()) == 58)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/tvv_proposal_form.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
        }
    }

    private void LogUserSelectHistory(Int64 ResultId, Int64 CompanyId)
    {
        UserSelectHistoryDB _userselectdb = new UserSelectHistoryDB();
        _userselectdb.LogUserSelectHistory("CI", Request.Browser.Type, Request.UserHostAddress, "CI", ResultId, CompanyId);
    }

    protected void gvCarResult_Sorting(object sender, GridViewSortEventArgs e)
    {
        SortGridViews(e.SortExpression);
    }

    private void SortGridViews(string strExpression)
    {
        if (Session[General.UserId] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] == null)
            {
                GetTempResultTableTwo();
            }
        }
        else
        {
            if (Cache["CarResult" + Session[General.CarId].ToString()] == null)
            {
                GetTempResultTableTwo();
            }
        }

        if (ViewState["SortOrder"] == null)
        {
            ViewState["SortOrder"] = SortDirection.Descending;
        }

        if (ViewState["SortExpression"] == null)
        {
            ViewState["SortExpression"] = SortDirection.Ascending.ToString();
        }

        DataView dv = new DataView();

        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);
        }
        string strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }
        else
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }

        dv.Sort = strExpression + strSort;
        gvCarResult.DataSource = dv;
        gvCarResult.DataBind();
    }

    protected void gvCarResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        #region NEW

        #endregion
        //For Thailand
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HtmlAnchor hplCallMe = (HtmlAnchor)e.Row.FindControl("hplCallMe");
            string _callMeCompanyName = "";
            string _callMeCoverType = "";
            string _callMeWorkShop = "";
            string _callMeAnnualPremium = "";
            string _callMeCompanyLogoUrl = "";
            string _callCarMakeModel = "";
            string _callCarProviderId = "";

            controls_usrMoreInfoDropdownButton btnMoreInfo = (controls_usrMoreInfoDropdownButton)e.Row.FindControl("ibtMoreInfo");
            btnMoreInfo.RowId = "NewRow" + ((e.Row.RowIndex * 2) + 2).ToString();
            string _companyId = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();
            ImageButton btnApplyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");
            _callCarProviderId = _companyId;



            HtmlGenericControl divFrame = new HtmlGenericControl("div");
            divFrame.Attributes.Add("id", "framework_moreinfo");

            HtmlGenericControl divContainer = new HtmlGenericControl("div");
            divContainer.Attributes.Add("id", "container_moreinfo");

            HtmlGenericControl divContent = new HtmlGenericControl("div");
            divContent.Attributes.Add("id", "content_moreinfo");

            Label lblPolicyInfoId = new Label();
            lblPolicyInfoId = (Label)e.Row.FindControl("lblPolicyInfoId");
            object _objPolicyinfoId = 4;//DataBinder.Eval(e.Row.DataItem, "NInfo3");

            Label lblPromoId = new Label();
            lblPromoId = (Label)e.Row.FindControl("lblPromoId");
            object _objPromoId = 11;//DataBinder.Eval(e.Row.DataItem, "NInfo2");

            Label lblPolicyId = new Label();
            lblPolicyId = (Label)e.Row.FindControl("lblPolicyId");
            object _objPolicyId = 5;//DataBinder.Eval(e.Row.DataItem, "NInfo1");

            int _coverid = 1;


            //CXCoverTypeId

            if (_objPolicyinfoId != null && _objPromoId != null && _objPolicyId != null)
            {


                CarPolicyInfo _carpolicyinfo = new CarPolicyInfo();
                CarPolicyInfoDB _carpolicyinfodb = new CarPolicyInfoDB();

                _carpolicyinfo = _carpolicyinfodb.GetProviderCarPolicyInfo(Convert.ToInt64(_objPolicyinfoId.ToString()));

                CarPromotion _carpromo = new CarPromotion();
                CarPromotionDB _carpromodb = new CarPromotionDB();

                _carpromo = _carpromodb.GetProviderCarPromotion(Convert.ToInt64(_objPromoId.ToString()));

                ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
                ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

                _policydoc = _policydocdb.GetProviderPolicyDocument(Convert.ToInt64(_objPolicyId.ToString()));

                if (_carpolicyinfo != null && _carpromo != null && _policydoc != null)
                {

                    //Policy Info
                    #region"Policy Info"

                    Label lblPolicyInfo = new Label();
                    lblPolicyInfo.Text = "";// "Policy Information";

                    Label labelPersonalAccident = new Label();
                    labelPersonalAccident.Text = "Personal accident limit  ";
                    labelPersonalAccident.Attributes.Add("class", "title");
                    Label lblPersonalAccident = new Label();
                    lblPersonalAccident.Text = "10000";//String.Format("{0:c0}", int.Parse(DataBinder.Eval(e.Row.DataItem, "PolicyHolder").ToString()));
                    lblPersonalAccident.Attributes.Add("class", "price");

                    Label labelWindscreen = new Label();
                    labelWindscreen.Text = "Windscreen excess  ";
                    labelWindscreen.Attributes.Add("class", "title");
                    Label lblWindscreen = new Label();

                    if (_companyId == "30") //Etiqa
                    {
                        lblWindscreen.Text = String.Format("{0:c0}", int.Parse(_carpolicyinfo.WindscreenAccess.ToString()));
                    }
                    else
                    {
                        lblWindscreen.Text = String.Format("{0:c0} + GST", int.Parse(_carpolicyinfo.WindscreenAccess.ToString()));
                    }

                    lblWindscreen.Attributes.Add("class", "price");

                    Label labelTowing = new Label();
                    labelTowing.Text = "Towing charges (accident only) ";
                    labelTowing.Attributes.Add("class", "title");
                    Label lblTowing = new Label();
                    lblTowing.Text = String.Format("{0:c0}", int.Parse(_carpolicyinfo.TowingCharges.ToString()));
                    lblTowing.Attributes.Add("class", "price");


                    Label labelExcess = new Label();
                    labelExcess.Text = "Excess breakdown  ";
                    labelExcess.Attributes.Add("class", "title");

                    Label labelNamed = new Label();
                    labelNamed.Text = "Named Driver ";
                    labelNamed.Attributes.Add("class", "title");
                    Label lblNamed = new Label();

                    lblNamed.Text = "10000";//String.Format("{0:c0}", int.Parse(DataBinder.Eval(e.Row.DataItem, "Excess").ToString()));
                    lblNamed.Attributes.Add("class", "price");

                    string _carcoverTypeDesc = DataBinder.Eval(e.Row.DataItem, "PackageName").ToString().Trim();

                    Label labelUnnamed = new Label();
                    labelUnnamed.Text = "Unnamed Driver  ";
                    labelUnnamed.Attributes.Add("class", "title");
                    //int _libertyDriverDiscountType = 0;
                    string Unnamedrate = "0";

                    Unnamedrate = "10000";//(float.Parse(DataBinder.Eval(e.Row.DataItem, "Excess").ToString()) + 500).ToString();
                    //NEED to change for each provider
                    /*
                    if (_companyId == "23") //HSBC
                    {
                        Unnamedrate = (float.Parse(DataBinder.Eval(e.Row.DataItem, "Excess").ToString()) + 500).ToString();
                    }
                    else if (_companyId == "30") //Etiqa
                    {
                        CarCapacityExcessClaim _cc = new CarCapacityExcessClaim();
                        CarCapacityExcessClaimDB _ccdb = new CarCapacityExcessClaimDB();

                        _cc = _ccdb.GetProviderCarCapacityExcessClaimEtiqa(Convert.ToInt64(_companyId), "Unnamed Driver",
                            Convert.ToInt32(Session[General.CarId].ToString()), Convert.ToInt32(Session[General.UserId].ToString()));

                        if (_cc != null)
                        {
                            Unnamedrate = _cc.ExcessAmount.ToString();
                        }
                        else if (_coverid == 2) //Panel
                        {
                            int Named = int.Parse(DataBinder.Eval(e.Row.DataItem, "Excess").ToString());
                            Unnamedrate = (Named * 4).ToString();
                        }
                        else
                        {
                            int Named = int.Parse(DataBinder.Eval(e.Row.DataItem, "Excess").ToString());
                            Unnamedrate = (Named * 2).ToString();

                        }
                    }
                    else if (_companyId == "29") //Liberty
                    {
                        if (DataBinder.Eval(e.Row.DataItem, "NInfo5") != null)
                        {
                            _libertyDriverDiscountType = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "NInfo5").ToString());
                        }

                        if (_libertyDriverDiscountType == 1 || _libertyDriverDiscountType == 2)
                        {
                            Unnamedrate = "Not applicable";
                        }
                        else
                        {
                            Unnamedrate = (float.Parse(DataBinder.Eval(e.Row.DataItem, "Excess").ToString()) + 500).ToString();
                        }
                    }


                    Label lblUnnamed = new Label();
                    if (_libertyDriverDiscountType == 1 || _libertyDriverDiscountType == 2)
                    {
                        lblUnnamed.Text = Unnamedrate;
                    }
                    else
                    {
                        lblUnnamed.Text = String.Format("{0:c0}", int.Parse(Unnamedrate));
                    }
                     * */
                    Label lblUnnamed = new Label();
                    lblUnnamed.Text = String.Format("{0:c0}", int.Parse(Unnamedrate));
                    lblUnnamed.Attributes.Add("class", "price");
                    Label labelExpiry = new Label();
                    labelExpiry.Text = "Quote expiry date  ";
                    labelExpiry.Attributes.Add("class", "title");
                    Label lblExpiry = new Label();

                    DateTime dtExpiryDays = DateTime.Now.AddDays(_carpolicyinfo.ExcessUnnamedDriver);

                    lblExpiry.Text = dtExpiryDays.ToString("dd/MMM/yyyy");
                    lblExpiry.Attributes.Add("class", "price");

                    Label labelCancellation = new Label();
                    labelCancellation.Text = "Cancellation penalty  ";
                    labelCancellation.Attributes.Add("class", "title");
                    Label lblCancellation = new Label();
                    lblCancellation.Text = String.Format("{0:c0} + GST", int.Parse(_carpolicyinfo.CancellationPenalty.ToString()));
                    lblCancellation.Attributes.Add("class", "price");

                    HtmlGenericControl _nextline = new HtmlGenericControl("div");
                    _nextline.InnerHtml = "<br /><br />";

                    HtmlGenericControl divclm = new HtmlGenericControl("div");
                    divclm.Attributes.Add("id", "clmn1");

                    HtmlGenericControl divtag = new HtmlGenericControl("div");
                    divtag.Attributes.Add("class", "body");

                    HtmlGenericControl divcopy = new HtmlGenericControl("div");
                    divcopy.Attributes.Add("class", "copy");
                    //divcopy.InnerHtml = "<br/><br/>";

                    HtmlGenericControl h1tag = new HtmlGenericControl("h1");

                    h1tag.Controls.Add(lblPolicyInfo);
                    divcopy.Controls.Add(h1tag);
                    divtag.Controls.Add(divcopy);

                    //HtmlGenericControl divitem = new HtmlGenericControl("div");
                    //divitem.Attributes.Add("class", "item");

                    //divitem.Controls.Add(labelPersonalAccident);
                    //divitem.Controls.Add(lblPersonalAccident);
                    //divtag.Controls.Add(divitem);

                    //HtmlGenericControl divitem2 = new HtmlGenericControl("div");
                    //divitem2.Attributes.Add("class", "item");

                    //divitem2.Controls.Add(labelWindscreen);
                    //divitem2.Controls.Add(lblWindscreen);
                    //divtag.Controls.Add(divitem2);

                    //HtmlGenericControl divitem3 = new HtmlGenericControl("div");
                    //divitem3.Attributes.Add("class", "item");

                    //divitem3.Controls.Add(labelTowing);
                    //divitem3.Controls.Add(lblTowing);
                    //divtag.Controls.Add(divitem3);

                    //HtmlGenericControl divitem4 = new HtmlGenericControl("div");
                    //divitem4.Attributes.Add("class", "item");

                    //HtmlGenericControl divsubitem = new HtmlGenericControl("div");
                    //divsubitem.Attributes.Add("class", "itemsub");

                    //divsubitem.Controls.Add(labelNamed);
                    //divsubitem.Controls.Add(lblNamed);

                    //HtmlGenericControl divxtra = new HtmlGenericControl("div");
                    //divxtra.Attributes.Add("class", "itemsub");
                    //HtmlGenericControl divxtra2 = new HtmlGenericControl("div");
                    //divxtra2.Attributes.Add("class", "itemsub");

                    //HtmlGenericControl divsubitem2 = new HtmlGenericControl("div");
                    //divsubitem2.Attributes.Add("class", "itemsub");

                    //divsubitem2.Controls.Add(labelUnnamed);
                    //divsubitem2.Controls.Add(lblUnnamed);

                    //divitem4.Controls.Add(labelExcess);
                    //divitem4.Controls.Add(divxtra);
                    //divitem4.Controls.Add(divsubitem);
                    //divitem4.Controls.Add(divxtra2);
                    //divitem4.Controls.Add(divsubitem2);

                    //divtag.Controls.Add(divitem4);

                    //HtmlGenericControl divitem5 = new HtmlGenericControl("div");
                    //divitem5.Attributes.Add("class", "item");

                    //divitem5.Controls.Add(labelExpiry);
                    //divitem5.Controls.Add(lblExpiry);
                    //divtag.Controls.Add(divitem5);

                    //HtmlGenericControl divitem6 = new HtmlGenericControl("div");
                    //divitem6.Attributes.Add("class", "item");

                    //divitem6.Controls.Add(labelCancellation);
                    //divitem6.Controls.Add(lblCancellation);
                    //divtag.Controls.Add(divitem6);

                    #region"button workshop"

                    HyperLink hplnkWorkshop = new HyperLink();
                    hplnkWorkshop.ImageUrl = Resources.ImageResource.WorkShopUrl;// "~/images/buttons/workshops.jpg";
                    hplnkWorkshop.Target = "_blank";

                    if (_companyId == "11")
                    {
                        // "Allianz C.P";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopEN");
                        }

                    }
                    else if (_companyId == "12")
                    {
                        //lblPromo.Text = "MSIG";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopEN");
                        }
                    }
                    else if (_companyId == "16")
                    {
                        //lblPromo.Text = "AXA";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopEN");
                        }
                    }
                    else if (_companyId == "29")
                    {
                        //lblPromo.Text = "LMG Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopEN");
                        }
                    }
                    else if (_companyId == "31")
                    {
                        //lblPromo.Text = "Chartis";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopEN");
                        }
                    }
                    else if (_companyId == "32")
                    {
                        //lblPromo.Text = "Bangkok Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopEN");
                        }
                    }
                    else if (_companyId == "33")
                    {
                        //lblPromo.Text = "MTI Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopTH");
                        }
                    }
                    else if (_companyId == "35")
                    {
                        
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KPIWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KPIWorkshopTH");
                        }
                    }
                    else if (_companyId == "39")
                    {

                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MittareWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MittareWorkshopEN");
                        }
                    }
                    else if (_companyId == "41")
                    {
                        //lblPromo.Text = KSK "Kurnia Insurance";  
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KSKWorkShopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KSKWorkShopTH");
                        }
                    }
                    else if (_companyId == "43")
                    {
                        //lblPromo.Text = "Syn Mun Kong Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SMKWorkShopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SMKWorkShopTH");
                        }
                    }
                    else if (_companyId == "45")
                    {
                        //lblPromo.Text = "Viriyah Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ViriyahWorkShopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ViriyahWorkShopTH");
                        }
                    }
                    else if (_companyId == "46")
                    {
                        //lblPromo.Text = "TMS Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopEH");
                        }
                    }
                    else if (_companyId == "50")
                    {
                        //lblPromo.Text = "TMS Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SCSMGWorkshopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SCSMGWorkshopEN");
                        }
                    }
                    else if (_companyId == "58")
                    {
                        //lblPromo.Text = "TMS Insurance";
                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatWorkShopTH");
                        }
                        else
                        {
                            hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatWorkShopEN");
                        }
                    }

                    HtmlGenericControl divitemworkshop = new HtmlGenericControl("h1");
                    divitemworkshop.Attributes.Add("class", "item");
                    divitemworkshop.Controls.Add(hplnkWorkshop);
                    divtag.Controls.Add(divitemworkshop);

                    //HyperLink hplnkViewPolicy = new HyperLink();
                    //lnkViewPolicy.ImageUrl = Resources.ImageResource.ViewPolicyUrl;//"~/images/buttons/download.jpg";

                    //HtmlGenericControl divitemViewPolicy = new HtmlGenericControl("h1");
                    //divitemViewPolicy.Attributes.Add("class", "item");
                    //divitemViewPolicy.Controls.Add(hplnkViewPolicy);
                    //divtag.Controls.Add(divitemViewPolicy);
                    #endregion

                    HtmlGenericControl nextline = new HtmlGenericControl("div");
                    nextline.InnerHtml = "<br />";

                    divtag.Controls.Add(nextline);

                    HtmlGenericControl divbottom = new HtmlGenericControl("div");
                    divbottom.Attributes.Add("class", "bottom");

                    HtmlGenericControl imgtag = new HtmlGenericControl("img");
                    imgtag.Attributes.Add("src", "/images/moreinfo/bg/clmn1_bottom.gif");
                    imgtag.Attributes.Add("width", "289px");
                    imgtag.Attributes.Add("height", "6");

                    divbottom.Controls.Add(imgtag);
                    divtag.Controls.Add(divbottom);
                    divclm.Controls.Add(divtag);

                    divContent.Controls.Add(divclm);

                    #endregion
                    //End of Policy Info



                    HtmlGenericControl divclm2 = new HtmlGenericControl("div");
                    divclm2.Attributes.Add("id", "clmn2");

                    HtmlGenericControl divtop = new HtmlGenericControl("div");
                    divtop.Attributes.Add("class", "top");

                    HtmlGenericControl divcopyMain = new HtmlGenericControl("div");
                    divcopyMain.Attributes.Add("class", "copy");
                    divcopyMain.InnerHtml = "<br/><br/>";


                    //Promotion

                    String strPromoDes = string.Empty;
                    Label lblPromo = new Label();
                    lblPromo.Text = _carpromo.PromotionTitle;
                    //Temporarily usage
                    if (_companyId == "11")
                    {
                        lblPromo.Text = Resources.MoreInfo.AZCP_Title; // "Allianz C.P";
                        strPromoDes = Resources.MoreInfo.AZCP_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.AZCP_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.AZCP_Line3;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.AZCP_Line4;
                    }
                    else if (_companyId == "12")
                    {
                        //lblPromo.Text = "MSIG";
                        lblPromo.Text = Resources.MoreInfo.MSIG_Title;
                        strPromoDes = Resources.MoreInfo.MSIG_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.MSIG_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.MSIG_Line3;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.MSIG_Line4;
                    }
                    else if (_companyId == "16")
                    {
                        //lblPromo.Text = "AXA";
                        lblPromo.Text = Resources.MoreInfo.AXA_Title;
                        strPromoDes = Resources.MoreInfo.AXA_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.AXA_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.AXA_Line3;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.AXA_Line4;
                    }
                    else if (_companyId == "29")
                    {
                        //lblPromo.Text = "LMG Insurance";
                        lblPromo.Text = Resources.MoreInfo.LMG_Title;

                        if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                        {
                            strPromoDes = Resources.MoreInfo.LMG_Line1;
                        }
                        else
                        {
                            strPromoDes = "LMG Insurance Co. Ltd, previously named Narai International Insurance Co. Ltd, "
                            + "was established on 27 November 1975. In 2003 the company merged with Kum Klao Insurance Public Co. Ltd and registered under the new name of LMG Insurance Co. Ltd "
                            + "on 6 September 2004.";
                        }

                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.LMG_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.LMG_Line3;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.LMG_Line4;
                    }
                    else if (_companyId == "31")
                    {
                        //lblPromo.Text = "Chartis";
                        lblPromo.Text = Resources.MoreInfo.Chartis_Title;
                        strPromoDes = Resources.MoreInfo.Chartis_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Chartis_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Chartis_Line3;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Chartis_Line4;
                    }
                    else if (_companyId == "32")
                    {
                        //lblPromo.Text = "Bangkok Insurance";
                        lblPromo.Text = Resources.MoreInfo.BKI_Title;
                        strPromoDes = Resources.MoreInfo.BKI_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.BKI_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.BKI_Line3;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.BKI_Line4;
                    }
                    else if (_companyId == "33")
                    {
                        lblPromo.Text = Resources.MoreInfo.MuangThai_Title;
                        strPromoDes = Resources.MoreInfo.MuangThai_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.MuangThai_Line2;

                    }
                    else if (_companyId == "35")
                    {
                        lblPromo.Text = Resources.MoreInfo.KPI_Title;
                        strPromoDes = Resources.MoreInfo.KPI_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.KPI_Line2;

                    }
                    else if (_companyId == "39")
                    {
                        lblPromo.Text = Resources.MoreInfo.Mittare_Title;
                        strPromoDes = Resources.MoreInfo.Mittare_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Mittare_Line2;

                    }
                    else if (_companyId == "41")
                    {
                        lblPromo.Text = Resources.MoreInfo.KSK_Title;
                        strPromoDes = Resources.MoreInfo.KSK_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.KSK_Line2;
                    }
                    else if (_companyId == "43")
                    {
                        lblPromo.Text = Resources.MoreInfo.SMK_Title;
                        strPromoDes = Resources.MoreInfo.SMK_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.SMK_Line2;

                    }
                    else if (_companyId == "45")
                    {
                        lblPromo.Text = Resources.MoreInfo.Viriyah_Title;
                        strPromoDes = Resources.MoreInfo.Viriyah_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Viriyah_Line2;

                    }
                    else if (_companyId == "46")
                    {
                        lblPromo.Text = Resources.MoreInfo.Tokio_Title;
                        strPromoDes = Resources.MoreInfo.Tokio_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Tokio_Line2;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Tokio_Line3;
                    }
                    else if (_companyId == "50")
                    {
                        lblPromo.Text = Resources.MoreInfo.SCSMG_Title;
                        strPromoDes = Resources.MoreInfo.SCSMG_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.SCSMG_Line2;

                    }
                    else if (_companyId == "58")
                    {
                        lblPromo.Text = Resources.MoreInfo.Thaivivat_Title;
                        strPromoDes = Resources.MoreInfo.Thaivivat_Line1;
                        strPromoDes = strPromoDes + "<br/> <br/>";
                        strPromoDes = strPromoDes + Resources.MoreInfo.Thaivivat_Line2;

                    }
                    //End Temporarily

                    Label lblPromoDesc = new Label();
                    lblPromoDesc.Text = strPromoDes.Replace("’", "");
                    HtmlGenericControl h1Tag = new HtmlGenericControl("h1");

                    h1Tag.Controls.Add(lblPromo);
                    divcopyMain.Controls.Add(h1Tag);

                    HtmlGenericControl _nextlineP = new HtmlGenericControl("div");
                    _nextlineP.InnerHtml = "<br />";

                    divcopyMain.Controls.Add(_nextlineP);
                    divcopyMain.Controls.Add(lblPromoDesc);
                    //End of Promotion

                    HtmlGenericControl h1Tag2 = new HtmlGenericControl("h1");

                    HtmlGenericControl divbottom2 = new HtmlGenericControl("div");
                    divbottom2.Attributes.Add("class", "bottom");

                    divclm2.Controls.Add(divtop);
                    divclm2.Controls.Add(divcopyMain);
                    divclm2.Controls.Add(divbottom2);


                    divContent.Controls.Add(divclm2);

                    HtmlGenericControl divFooter = new HtmlGenericControl("div");
                    divFooter.Attributes.Add("id", "footerMoreInfo");


                    HyperLink hplnkClose = new HyperLink();
                    hplnkClose.ImageUrl = "/images/moreinfo/nav/spacer.gif";
                    hplnkClose.NavigateUrl = "javascript:HideRowMoreInfo(" + ((e.Row.RowIndex * 2) + 2).ToString() + ");";
                    hplnkClose.Width = 125;
                    hplnkClose.Height = 35;

                    divFooter.Controls.Add(hplnkClose);

                    divContainer.Controls.Add(divContent);
                    divFrame.Controls.Add(divContainer);
                    divFrame.Controls.Add(divFooter);

                    StringWriter swMain = new StringWriter();
                    HtmlTextWriter wMain = new HtmlTextWriter(swMain);

                    divFrame.RenderControl(wMain);
                    string sMain = swMain.GetStringBuilder().ToString();

                    btnMoreInfo.MoreInfo = sMain.Replace("'", "\"");
                }
            }
            //Company Logo and Cover Type
            Label lblCoverTypeDesc = (Label)e.Row.FindControl("lblPackageName");
            Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");




            string _logoUrl = DataBinder.Eval(e.Row.DataItem, "CompanyLogoServerUrl").ToString();
            string _coverTypeDesc = DataBinder.Eval(e.Row.DataItem, "PackageName").ToString().Trim();

            imgCompanyLogo.ImageUrl = _logoUrl;
            imgCompanyLogo.ToolTip = _coverTypeDesc;
            lblCoverTypeDesc.Text = _coverTypeDesc;
            _callMeCoverType = _coverTypeDesc;
            _callCarMakeModel = lblCarMakemodel.Text;

            //// DEC
            Label lblDEC = (Label)e.Row.FindControl("lblDEC");
            Label lblDECSymbol = (Label)e.Row.FindControl("lblDECSymbol");
            Label lblDECZero = (Label)e.Row.FindControl("lblDECZero");
            string _DEC = DataBinder.Eval(e.Row.DataItem, "DEC").ToString().Trim();

            if (_DEC != null && _DEC != string.Empty && Convert.ToSingle(_DEC) > 0.0f)
            {
                lblDECZero.Visible = false;
                lblDEC.Text = Convert.ToInt32(_DEC).ToString("#,000");//Resources.CarInsuranceResultPage.Waived;    
                lblDEC.Visible = true;
                lblDECSymbol.Visible = true;
            }
            else
            {
                lblDECZero.Visible = true;
                lblDEC.Text = "0";
                lblDEC.Visible = false;
                lblDECSymbol.Visible = false;
            }
            //// END DEC
            string _promotion = DataBinder.Eval(e.Row.DataItem, "PromotionPrice").ToString().Trim();
            string _premium = DataBinder.Eval(e.Row.DataItem, "AnnualPremium").ToString().Trim();

            Label lblPromotionPrice = (Label)e.Row.FindControl("lblPromotionPrice");
            Label lblPremiumPrice = (Label)e.Row.FindControl("lblPremiumPrice");
            Label lblPremiumPromotion = (Label)e.Row.FindControl("lblPremiumPromotion");
            Label lblSavePrice = (Label)e.Row.FindControl("lblSavePrice");

            Label lblPremiumSave = (Label)e.Row.FindControl("lblPremiumSave");

            lblPromotionPrice.Text = Convert.ToSingle(_promotion).ToString("#,000.00");                
            lblPremiumPrice.Text = Convert.ToSingle(_premium).ToString("#,000.00");
            lblSavePrice.Text = Convert.ToSingle(Convert.ToSingle(_premium) - Convert.ToSingle(_promotion)).ToString("#,##0.00");

            if (_promotion == _premium)
            {
                 lblPremiumPromotion.Visible = false;
                 lblPremiumSave.Visible = false;
                 lblSavePrice.Visible = false; 
            }
           
            ///SUM INSURED OR OWN DAMAGE FIRE OR THIEF
            Label lblSumInsured = (Label)e.Row.FindControl("lblSumInsured");
            Label lblSumInsuredSymbol = (Label)e.Row.FindControl("lblSumInsuredSymbol");
            Image imgSumInsured = (Image)e.Row.FindControl("imgSumInsured");
            string _sumInsured = DataBinder.Eval(e.Row.DataItem, "SumInsured").ToString().Trim();

            if (_sumInsured != null && _sumInsured != string.Empty && Convert.ToSingle(_sumInsured) > 0.0f)
            {
                imgSumInsured.Visible = false;
                lblSumInsured.Text = Convert.ToInt32(_sumInsured).ToString("#,000");  //_sumInsured;
                lblSumInsured.Visible = true;
                lblSumInsuredSymbol.Visible = true;
            }
            else
            {
                imgSumInsured.Visible = true;
                lblSumInsured.Text = "0";
                lblSumInsured.Visible = false;
                lblSumInsuredSymbol.Visible = false;
            }
            Image imgFloodCover = (Image)e.Row.FindControl("imgFloodCover");
            if (DataBinder.Eval(e.Row.DataItem, "IsFloodCover").ToString () == "0")
            {
                imgFloodCover.ImageUrl = "/images/icon/x.png";
            }


            Label lblFire = (Label)e.Row.FindControl("lblFire");
            Label lblFireSymbol = (Label)e.Row.FindControl("lblFireSymbol");
            Image imgFire = (Image)e.Row.FindControl("imgFire");
            string _fire = DataBinder.Eval(e.Row.DataItem, "Fire").ToString().Trim();

            if (_fire != null && _fire != string.Empty && Convert.ToSingle(_fire) > 0.0f)
            {
                imgFire.Visible = false;
                lblFire.Text = Convert.ToInt32(_fire).ToString("#,000");  //_sumInsured;
                lblFire.Visible = true;
                //lblFireSymbol.Visible = true;
            }
            else
            {
                imgFire.Visible = true;
                lblFire.Text = "0";
                lblFire.Visible = false;
                //lblFireSymbol.Visible = false;
            }
            Label lblTheft = (Label)e.Row.FindControl("lblTheft");
            Label lblTheftSymbol = (Label)e.Row.FindControl("lblTheftSymbol");
            Image imgTheft = (Image)e.Row.FindControl("imgTheft");
            string _theft = DataBinder.Eval(e.Row.DataItem, "Theft").ToString().Trim();

            if (_theft != null && _theft != string.Empty && Convert.ToSingle(_theft) > 0.0f)
            {
                imgTheft.Visible = false;
                lblTheft.Text = Convert.ToInt32(_fire).ToString("#,000");  //_sumInsured;
                lblTheft.Visible = true;
                //lblFireSymbol.Visible = true;
            }
            else
            {
                imgTheft.Visible = true;
                lblTheft.Text = "0";
                lblTheft.Visible = false;
                //lblFireSymbol.Visible = false;
            }
            ///END SUM INSURED OR OWN DAMAGE FIRE OR THIEF

            _callMeAnnualPremium = String.Format("${0:0,0.00}", Convert.ToSingle(DataBinder.Eval(e.Row.DataItem, "AnnualPremium")));
            if (_callCarProviderId == "11")
            {
                _callMeCompanyName = "Allianz C.P";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;// "/images/callme/heading_allianz.gif";
            }
            else if (_callCarProviderId == "12")
            {
                _callMeCompanyName = "MSIG";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker; //"/images/callme/heading_msig.gif";
            }
            else if (_callCarProviderId == "16")
            {
                _callMeCompanyName = "AXA";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker; //"/images/callme/heading_axa.gif";
            }
            else if (_callCarProviderId == "29")
            {
                _callMeCompanyName = "LMG Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_lmg.gif";
            }
            else if (_callCarProviderId == "31")
            {
                _callMeCompanyName = "Chartis";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker; //"/images/callme/heading_chartis.gif";
            }
            else if (_callCarProviderId == "32")
            {
                _callMeCompanyName = "Bangkok Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "33")
            {
                _callMeCompanyName = "Muang Thai Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "35")
            {
                _callMeCompanyName = "Krungthai Panich Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "39")
            {
                _callMeCompanyName = "Mittare Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "41")
            {
                _callMeCompanyName = "KSK Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "43")
            {
                _callMeCompanyName = "Syn Mun Kong Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "45")
            {
                _callMeCompanyName = "Viriyah Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "46")
            {
                _callMeCompanyName = "Tokio Marine SriMuang Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else if (_callCarProviderId == "50")
            {
                _callMeCompanyName = "Siam Commercial Samaggi Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  
            }
            else if (_callCarProviderId == "58")
            {
                _callMeCompanyName = " Thaivivat Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_bangkok.gif";
            }
            else
            {
                _callMeCompanyName = "CompareXpress Insurance";
                _callMeCompanyLogoUrl = Resources.ImageResource.CallMeBroker;  //"/images/callme/heading_liberty.gif";
                _callMeCoverType = "";
            }

            hplCallMe.Attributes.Add("onclick", "ShowHideCallMe(true, '" + _callMeCompanyName + "', '" + _callMeAnnualPremium + "', '" + _callMeCoverType.Replace("'", "\\'") + "', '" + _callMeWorkShop + "','" + _callMeCompanyLogoUrl + "','" + _callCarMakeModel + "','" + _callCarProviderId + "');");
        }
    }
    
    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        #region "Call Me"
        //FullName
        if (rfvCallMeFullName.Enabled && rfvCallMeFullName.ValidationGroup == strValidationGroup)
        {
            rfvCallMeFullName.Validate();
            if (rfvCallMeFullName.IsValid == false)
            {
                txtCallMeFullName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtCallMeFullName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtCallMeFullName.ControlStyle.CssClass = "";
        }

        if (revCallMeFullName.Enabled && revCallMeFullName.ValidationGroup == strValidationGroup)
        {
            if (rfvCallMeFullName.IsValid)
            {
                revCallMeFullName.Validate();
                if (revCallMeFullName.IsValid == false)
                {
                    txtCallMeFullName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtCallMeFullName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtCallMeFullName.ControlStyle.CssClass = "";
        }

        //Time
        if (rfvCallMeTime.Enabled && rfvCallMeTime.ValidationGroup == strValidationGroup)
        {
            rfvCallMeTime.Validate();
            if (rfvCallMeTime.IsValid == false)
            {
                ddlCallMeTime.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlCallMeTime.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlCallMeTime.ControlStyle.CssClass = "";
        }

        //Mobile Number
        usrCallMePhoneNo.ChangeValidationEffectServerSide(strValidationGroup);
        #endregion

        #region Personal Details

        //FullName
        if (rfvFullName.Enabled && rfvFullName.ValidationGroup == strValidationGroup)
        {
            rfvFullName.Validate();
            if (rfvFullName.IsValid == false)
            {
                txtFullName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtFullName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtFullName.ControlStyle.CssClass = "";
        }

        if (revFullName.Enabled && revFullName.ValidationGroup == strValidationGroup)
        {
            if (rfvFullName.IsValid)
            {
                revFullName.Validate();
                if (revFullName.IsValid == false)
                {
                    txtFullName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtFullName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtFullName.ControlStyle.CssClass = "";
        }

        //NRIC Number
        ddlIdNumber.ChangeValidationEffectServerSide(strValidationGroup);

        //Vehicle No
        if (rfvVehicleNo.Enabled && rfvVehicleNo.ValidationGroup == strValidationGroup)
        {
            rfvVehicleNo.Validate();
            if (rfvVehicleNo.IsValid == false)
            {
                txtVehicleNo.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtVehicleNo.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtVehicleNo.ControlStyle.CssClass = "";
        }

        if (revVehicleNo.Enabled && revVehicleNo.ValidationGroup == strValidationGroup)
        {
            if (rfvVehicleNo.IsValid)
            {
                revVehicleNo.Validate();
                if (revVehicleNo.IsValid == false)
                {
                    txtVehicleNo.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtVehicleNo.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtVehicleNo.ControlStyle.CssClass = "";
        }

        if (csvVehicleNo.Enabled && csvVehicleNo.ValidationGroup == strValidationGroup)
        {
            if (rfvVehicleNo.IsValid && revVehicleNo.IsValid)
            {
                csvVehicleNo.Validate();
                if (csvVehicleNo.IsValid == false)
                {
                    txtVehicleNo.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtVehicleNo.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtVehicleNo.ControlStyle.CssClass = "";
        }

        //Mobile Number
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);

        #endregion
    }

    protected void CheckVehicleNumber(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        //_carregno = null;
    }

    protected void ibtSubmit_Click(object sender, ImageClickEventArgs e)
    {
    }

    protected void ibtCallMeConfirm_Click(object sender, ImageClickEventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.CarId] != null)
        {
            string _message = "";
            string _title = "";
            string _ec = "";
            txtCallMeFullName.Text = General.ClearScriptTag(txtCallMeFullName.Text);

            ChangeValidationEffectServerSide("callme");
            if (IsValid)
            {
                Int64 _result = 0;
                ContactUser _cu = new ContactUser();
                ContactUserDB _cudb = new ContactUserDB();

                _cu = _cudb.GetCallMe(Convert.ToInt64(Session[General.UserId].ToString()), Convert.ToInt64(Session[General.CarId].ToString()), "CI-" + lblInsuranceType.Text, Convert.ToInt64(CompanyId.Value));

                if (_cu != null)
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "Alert", "alert('You have already requested to call you.'  + '\\r\\n' + 'Please wait a while to get call from them. Thank you.')", true);
                }
                else
                {
                    ContactUser _contactuser = new ContactUser();
                    ContactUserDB _contactuserdb = new ContactUserDB();

                    _contactuser.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                    _contactuser.ProductId = Convert.ToInt64(Session[General.CarId].ToString());

                    #region callme
                    //long providerId = Convert.ToInt16(Request.Form["CompanyId"]);
                    if (CompanyId.Value == "11") //AZCP
                    {
                        _contactuser.ProviderCompanyId = 11;
                        _ec = "1011";
                    }
                    else if (CompanyId.Value == "12")//MSIG
                    {
                        _contactuser.ProviderCompanyId = 12;
                        _ec = "1012";
                    }
                    else if (CompanyId.Value == "16")//AXA
                    {
                        _contactuser.ProviderCompanyId = 16;
                        _ec = "1016";
                    }
                    else if (CompanyId.Value == "29")//LMG
                    {
                        _contactuser.ProviderCompanyId = 29;
                        _ec = "1029";
                    }
                    else if (CompanyId.Value == "31")//Chartis
                    {
                        _contactuser.ProviderCompanyId = 31;
                        _ec = "1031";
                    }
                    else if (CompanyId.Value == "32")//BKI
                    {
                        _contactuser.ProviderCompanyId = 32;
                        _ec = "1032";
                    }
                    else if (CompanyId.Value == "33")//MuangThai
                    {
                        _contactuser.ProviderCompanyId = 33;
                        _ec = "1033";
                    }
                    else if (CompanyId.Value == "35")//Krungthai
                    {
                        _contactuser.ProviderCompanyId = 35;
                        _ec = "1035";
                    }
                    else if (CompanyId.Value == "39")//Mittare
                    {
                        _contactuser.ProviderCompanyId = 39;
                        _ec = "1039";
                    }
                    else if (CompanyId.Value == "41")//KSK
                    {
                        _contactuser.ProviderCompanyId = 41;
                        _ec = "1041";
                    }
                    else if (CompanyId.Value == "43")//Synmunkong
                    {
                        _contactuser.ProviderCompanyId = 43;
                        _ec = "1043";
                    }
                    else if (CompanyId.Value == "45")//Viriyah
                    {
                        _contactuser.ProviderCompanyId = 45;
                        _ec = "1045";
                    }
                    else if (CompanyId.Value == "46")//Tokio Marine Srimuang
                    {
                        _contactuser.ProviderCompanyId = 46;
                        _ec = "1046";
                    }
                    else if (CompanyId.Value == "50")//SCSMG
                    {
                        _contactuser.ProviderCompanyId = 50;
                        _ec = "1050";
                    }
                    else if (CompanyId.Value == "58")//Thaivivat
                    {
                        _contactuser.ProviderCompanyId = 58;
                        _ec = "1058";
                    }
                    //for test only
                    //else 
                    //{                     
                    //    _contactuser.ProviderCompanyId = 30;
                    //    _ec = "1030";
                    //}

                    _contactuser.InsuranceType = "CI-" + lblInsuranceType.Text;
                    _contactuser.FullName = txtCallMeFullName.Text.Trim();
                    _contactuser.ContactNo = usrCallMePhoneNo.GetPhoneNo();
                    _contactuser.CallTime = Convert.ToInt16(ddlCallMeTime.Text);
                    _contactuser.Status = true;

                    _result = _contactuserdb.Insert(_contactuser);
                    if (_result > 0)
                    {
                        string _emailList;
                        _message = "Dear Sir/Madam,";
                        
                       
                        //Regex objEnglish=new Regex(@"^[a-zA-Z0-9_]+$");                        
                        Regex objEnglish = new Regex(@"^[a-zA-Z0-9'/\\&.\s-]+$");

                        if (Session["Language"].ToString() == "en-US" && objEnglish.IsMatch(txtCallMeFullName.Text.ToString()))
                        {   //Farang case  [English name]
                            _title = "Foreigner Case - Call Me request by " + txtCallMeFullName.Text + " for " + inputCallMeCompanyName.Value;
                            _emailList = ConfigurationManager.AppSettings["TH.CICallMeBack"].ToString();
                            //_emailList = "cx.thailand@gmail.com";
                            _message += "<br/>";
                            _message += "<br/><b>We consider this as direct lead (GG brokers cannot see this lead)</b>";
                            _message += "<br/>";
                        }
                        else
                        {   
                            _title = "Call Me request by " + txtCallMeFullName.Text + " for " + inputCallMeCompanyName.Value;
                            _emailList = ConfigurationManager.AppSettings["TH.CICallMeMessageReceiver"].ToString();  
                            //_emailList = "cx.thailand@gmail.com";
                        }

                        _message += "<br/><br/>Customer Name: " + txtCallMeFullName.Text;
                        _message += "<br/><br/>Make/Model : " + inputCallMeMakeModel.Value;
                        _message += "<br/><br/>Insurer : " + inputCallMeCompanyName.Value;
                        _message += "<br/><br/>Contact No : " + usrCallMePhoneNo.GetPhoneNo();
                        _message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                        _message += "<br/><br/><br/>GluayGluay.com support";

                        MyMailManager.SendNotification(_emailList, _title, _message);
                        //Response.Redirect("~/user/usermessage.aspx?mt=CI&ec=" + _ec);
                        _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                        Session["UMMSG"] = "CI," + _ec.ToString();
                        Response.Redirect(_redirectUrl);
                    }
                    #endregion
                }
            }
        }
    }

    private void CheckValidation()
    {
        if (divUserRefDetail.Visible == true)
        {
            rfvFullName.Enabled = true;
            revFullName.Enabled = true;
            ddlIdNumber.IsEnableValidation(true);
            txtMobileNo.IsEnableValidation(true);
        }
        else if (divUserRefDetail.Visible == false)
        {
            rfvFullName.Enabled = false;
            revFullName.Enabled = false;
            ddlIdNumber.IsEnableValidation(false);
            txtMobileNo.IsEnableValidation(false);
        }

        Page.Validate();
    }

    protected void GenerateExcelQuote(string FilePath, string FileName)
    {
    }

    public string GetFilePath()
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("FileOutputPath").ToString();
        _filePath += "exceloutput\\car_nomatch\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _todaydate = DateTime.Now.ToString("yyyyMMMdd");
        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        return _filePath;
    }

    private void SendMailNotification(CarDetailTH car)
    { 
        string _message = "";
        string _title = "GG - Foreigner case";
        _message += "Dear Sir/Madam,";
        _message += "<br/>";
        _message += "<br/><br/><b>We consider this as direct lead (GG brokers cannot see this lead)</b>";
        _message += "<br/><br/>First Name : " + car.Info8;
        _message += "<br/><br/>SurName : " + car.Info7;
        _message += "<br/><br/>Email : " + car.Info5;
        _message += "<br/><br/>Mobile : " + car.Info6;
        _message += "<br/><br/>Car Model : " + car.CarMakeName + " " + car.CarModelName;
        //_message += "<br/><br/>";
        _message += "<br/><br/>GluayGluay.com support";

        string _emailList = ConfigurationManager.AppSettings["TH.CICallMeMessageReceiver"].ToString();
        MyMailManager.SendCRMMessage(_emailList, _title, _message);
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        if (lblInsuranceType.Text == "1")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/your-details.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
        else if (lblInsuranceType.Text == "2+")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/class-2plus.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
        else if (lblInsuranceType.Text == "3")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/class-3.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
        else if (lblInsuranceType.Text == "3+")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/class-3plus.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
        else
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/class-1single.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
    }
}
